const { Sequelize, DataTypes } = require('sequelize');

// 数据库配置
const config = {
  dialect: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  database: 'lingxi_system',
  username: 'root',
  password: 'root',  // 尝试使用root密码
  timezone: '+08:00',
  define: {
    charset: 'utf8mb4',
    dialectOptions: {
      collate: 'utf8mb4_unicode_ci',
    },
    timestamps: true,
  },
};

// 创建Sequelize实例
const sequelize = new Sequelize(config);

async function checkSuppliersTable() {
  try {
    console.log('连接到数据库...');
    await sequelize.authenticate();
    console.log('数据库连接成功!');

    // 查询suppliers表结构
    console.log('\n查询suppliers表结构...');
    const [results] = await sequelize.query('DESCRIBE suppliers');
    
    console.log('\nsuppliers表结构:');
    console.table(results);
    
    // 检查是否有organization_id字段
    const hasOrganizationId = results.some(row => row.Field === 'organization_id');
    console.log(`\n是否有organization_id字段: ${hasOrganizationId ? '是' : '否'}`);
    
    if (!hasOrganizationId) {
      console.log('\n建议添加organization_id字段:');
      console.log('ALTER TABLE suppliers ADD COLUMN organization_id INT NOT NULL DEFAULT 1;');
    }
    
  } catch (error) {
    console.error('操作失败:', error.message);
    
    // 如果使用root密码失败，尝试空密码
    if (error.message.includes('Access denied')) {
      console.log('\n尝试使用空密码连接...');
      const config2 = {
        ...config,
        password: ''
      };
      
      const sequelize2 = new Sequelize(config2);
      try {
        await sequelize2.authenticate();
        console.log('使用空密码连接成功!');
        
        // 查询suppliers表结构
        console.log('\n查询suppliers表结构...');
        const [results] = await sequelize2.query('DESCRIBE suppliers');
        
        console.log('\nsuppliers表结构:');
        console.table(results);
        
        // 检查是否有organization_id字段
        const hasOrganizationId = results.some(row => row.Field === 'organization_id');
        console.log(`\n是否有organization_id字段: ${hasOrganizationId ? '是' : '否'}`);
        
        if (!hasOrganizationId) {
          console.log('\n建议添加organization_id字段:');
          console.log('ALTER TABLE suppliers ADD COLUMN organization_id INT NOT NULL DEFAULT 1;');
        }
      } catch (error2) {
        console.error('使用空密码连接也失败:', error2.message);
      } finally {
        await sequelize2.close();
      }
    }
  } finally {
    await sequelize.close();
  }
}

checkSuppliersTable();